<?php
namespace Ardon\EucpSms;

class MagicCrypt
{
    //加密
    public static function encrypt($encryptStr)
    {
        if(version_compare(PHP_VERSION,'7.0.0','ge'))
        {
            return self::encryptPhp7($encryptStr);//加密结果
        }

        $localIV = config('eucpsms.iv');
        $encryptKey = config('eucpsms.ym_sms_aespwd');

        if (true == config('eucpsms.en_gzip'))   $encryptStr = gzencode($encryptStr);

        //Open module
        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, $localIV);

        mcrypt_generic_init($module, $encryptKey, $localIV);

        //Padding
        $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad
        $encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples

        //encrypt
        $encrypted = mcrypt_generic($module, $encryptStr);

        //Close
        mcrypt_generic_deinit($module);
        mcrypt_module_close($module);

        return $encrypted;
    }

    //PHP7使用这个加密
    public static function encryptPhp7($encryptStr)
    {
        $localIV = config('eucpsms.iv');
        $encryptKey = config('eucpsms.ym_sms_aespwd');

        if (true == config('eucpsms.en_gzip'))
        {
            $encryptStr = gzencode($encryptStr);
        }

        return openssl_encrypt($encryptStr, 'AES-128-ECB', $encryptKey, OPENSSL_RAW_DATA, $localIV);
    }

    //解密
    public static function decrypt($encryptStr) {

        if (version_compare(PHP_VERSION,'7.0.0','ge'))
        {
            return self::decryptPhp7($encryptStr);//加密结果
        }

        $localIV = config('eucpsms.iv');
        $encryptKey = config('eucpsms.ym_sms_aespwd');

        //Open module
        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, $localIV);

        mcrypt_generic_init($module, $encryptKey, $localIV);

        $encryptedData = mdecrypt_generic($module, $encryptStr);

        if (true == config('eucpsms.en_gzip'))
        {
            $encryptedData = gzdecode($encryptedData);
        }

        return $encryptedData;
    }

    //PHP7使用这个解密
    public static function decryptPhp7($encryptStr)
    {
        $localIV = config('eucpsms.iv');
        $encryptKey = config('eucpsms.ym_sms_aespwd');
        $encryptedData = openssl_decrypt($encryptStr, 'AES-128-ECB', $encryptKey, OPENSSL_RAW_DATA, $localIV);
        if (true == config('eucpsms.en_gzip'))
        {
            $encryptedData = gzdecode($encryptedData);
        }
        return $encryptedData;
    }

}
